# -*- coding: utf-8 -*-
# 引入依赖包
# pip install alibabacloud_imagerecog20190930

import os
import io
from urllib.request import urlopen
from alibabacloud_imagerecog20190930.client import Client
from alibabacloud_imagerecog20190930.models import ClassifyingRubbishAdvanceRequest
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions

config = Config(
    access_key_id=os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID"),
    access_key_secret=os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
    # 访问的域名
    endpoint="imagerecog.cn-shanghai.aliyuncs.com",
    # 访问的域名对应的region
    region_id="cn-shanghai",
)


def alibaba_garbage():  # 定义函数
    # 场景一：文件在本地
    #img = open(r"/home/orangepi/tmp/test.png", "rb")  # 打开图片文件
    # 获取当前工作目录
    current_dir = os.getcwd()
    # 构建图片文件的完整路径
    file_path = os.path.join(current_dir, "ClassifyingRubbish1.jpg")
    # 打开图片文件
    img = open(file_path, "rb")
    classifying_rubbish_request = ClassifyingRubbishAdvanceRequest()
    classifying_rubbish_request.image_urlobject = img
    runtime = RuntimeOptions()
    try:
        # 初始化Client
        client = Client(config)
        response = client.classifying_rubbish_advance(
            classifying_rubbish_request, runtime
        )
        print(response.body.to_map()["Data"]["Elements"][0]["Category"])  # 获取垃圾种类
        return response.body.to_map()["Data"]["Elements"][0]["Category"]  # 返回垃圾种类
    except Exception as error:
        print(type("获取失败"))  # 返回失败信息
        return "获取失败"


if __name__ == "__main__":  # 主函数
    alibaba_garbage()  # 调用函数
